package com.brkj.download;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.brkj.model.DS_Course;
import com.brkj.util.view.BaseActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class CourseDownloader {
	
	private static CourseDownloader mDownloader;
	private Context context;
	
	private Map<String, CourseDLUnit> DLMap=  new HashMap<String, CourseDLUnit>();
	
	private CourseDownloader(Context context){
		this.context = context;
	}

	public static CourseDownloader Create(Context context) {
		if(mDownloader == null){
			mDownloader = new CourseDownloader(context);
		}

		return mDownloader;
	}
	

	public int Download(DS_Course course) {
		int courseID = course.getCourseID();
		CourseDLUnit dlUnit = new CourseDLUnit(context, courseID);
		
		//等于1 为已下载
		int result = dlUnit.Download(course);
		if(result != 1){
			DLMap.put(Integer.toString(courseID), dlUnit);
		}
		
		return result;
	}
	
	public void StartDownload(int courseID, TextView progressView){
		if(DLMap.containsKey(Integer.toString(courseID))){  //已有下载实例
			DLMap.get(Integer.toString(courseID)).StartDL();
		}else{
			CourseDLUnit dlUnit = new CourseDLUnit(context, courseID); //新实例， 按课程id下载
			if(dlUnit.DownloadByID(courseID, progressView) == 0){
				((BaseActivity)context).showToast("下载错误！");
			}else{
				DLMap.put(Integer.toString(courseID), dlUnit);
			}
		}
		
	}
	
	public void RemoveDownloadFinishedCourse(int courseID){
		DLMap.remove(Integer.toString(courseID));
	}
	

	public void PauseDownload(int courseID){
		if(DLMap.containsKey(Integer.toString(courseID))){
			DLMap.get(Integer.toString(courseID)).PauseDL();
		}
	}
	
	public void DeleteDowlod(int courseID){
		if(DLMap.containsKey(Integer.toString(courseID))){  //已有下载实例
			DLMap.get(Integer.toString(courseID)).DeleteDL();
		}else{
			CourseDLUnit dlUnit = new CourseDLUnit(context, courseID); 
			dlUnit.DeleteDL();
		}
	}
	
	public void SetDownloadingView(int courseId, View view) {
		if(DLMap.containsKey(Integer.toString(courseId))){
			DLMap.get(Integer.toString(courseId)).SetDownloadingView(view);
		}

	}

	public boolean getDLState(int courseID) {
		if(DLMap.containsKey(Integer.toString(courseID))){
			return DLMap.get(Integer.toString(courseID)).GetDLSate();
		}
		return false;
	}
	

}
